package com.ljf.game.interceprot;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;


/**
 * WebSocket 握手的前置拦截器
 */
public class WebSocketInterceptor implements HandshakeInterceptor {

	// 握手之前触发 (return true 才会握手成功 )
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
			Map<String, Object> attr) {

		String username = ((ServletServerHttpRequest) request).getServletRequest().getParameter("username");
		if (username == null || username.isEmpty())
			throw new RuntimeException("没有用户名，请添加?username=***");
		attr.put("username",username);
		return true;
	}

	// 握手之后触发
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		String username = ((ServletServerHttpRequest) request).getServletRequest().getParameter("username");
		System.out.println("连接成功，用户【"+username+"】");
		// TODO 记录请求信息

	}

}
